#include "RFID.h"
#include "usart.h"

uint8_t RFID_ID[4]; // 卡号

// 校验和检测
static uint8_t CheckSum(uint8_t *ptr, uint8_t len)
{
    uint8_t i;
    uint8_t checksum = 0;

    for (i = 0; i < (len - 1); i++)
    {
        checksum ^= ptr[i];
    }
    checksum = ~checksum;
    if (ptr[len - 1] == checksum)
        return 1; // OK
    else
        return 0; // ERR
}

void RFID_UART_Callback(uint8_t *pData, uint8_t Size)
{
    // 判断校验和是否正确
    if (CheckSum(pData, 12))
    {
        // 判断是否接收数据
        if ((pData[0] == 0x04) && (pData[1] == 0x0C) && (pData[2] == 0x02) && (pData[3] == 0x20)) //对数据包进行判断
        {
            // 获取卡号
            for (uint8_t i = 0; i < 4; i++) //获取4字节卡号
            {
                RFID_ID[i] = pData[i + 7]; //从数组的第7个字节开始为卡号，共4字节
            }

            RFID_Function(RFID_ID);
        }
    }

    HAL_UARTEx_ReceiveToIdle_IT(&RFID_UART, pData, 32);
}

void RFID_SetBuzzer(void)
{
    uint8_t cmd[8];
    cmd[0] = 0x03;
    cmd[1] = 0x08;
    cmd[2] = 0xC2;
    cmd[3] = RFID_ADDRESS;
    cmd[4] = 0x01;
    cmd[5] = 0x00;
    cmd[6] = 0x00;
    cmd[7] = 0x17;
    HAL_UART_Transmit(&RFID_UART, cmd, 8, HAL_MAX_DELAY);
}

void RFID_ResetBuzzer(void)
{
    uint8_t cmd[8];
    cmd[0] = 0x03;
    cmd[1] = 0x08;
    cmd[2] = 0xC2;
    cmd[3] = RFID_ADDRESS;
    cmd[4] = 0x00;
    cmd[5] = 0x00;
    cmd[6] = 0x00;
    cmd[7] = 0x16;
    HAL_UART_Transmit(&RFID_UART, cmd, 8, HAL_MAX_DELAY);
}
